#!/usr/bin/env bash
# Copyright (c) 2021 The Toltec Contributors
# SPDX-License-Identifier: MIT

pkgnames=(plato)
pkgdesc="Document reader"
url=https://github.com/LinusCDE/plato
pkgver=0.9.34-2
timestamp=2023-03-08T17:58Z
section="readers"
maintainer="Linus K. <linus@cosmos-ink.net>"
license=AGPL-3.0-or-later
installdepends=(display jq)
makedepends=(build:jq build:unzip build:wget build:patchelf)
flags=(patch_rm2fb)

image=rust:v2.3.1
source=("https://github.com/LinusCDE/plato/archive/${pkgver%-*}-rm-release-13.zip")
sha256sums=(82ef5786704ecdb4fe11ce16e7e4ae10b518a592965c292977bb33962c891d48)

build() {
    # 'cargo pkgid' seems to output something different with most
    # recent nightly builds. This adjusts the filtering.
    sed -i "s/version=.*$/version=\'$(cargo pkgid -p plato | cut -d "#" -f 2 | cut -d ":" -f 2)\'/g" download.sh

    # Temporary fix until next release (TODO: Remove for next released version as included with commit fbfaf3d7)
    sed -i "s/--target=arm-unknown-linux-gnueabihf/--target=armv7-unknown-linux-gnueabihf/g" build.sh

    # Use our toolchain
    export AR=arm-linux-gnueabihf-ar
    export CC=arm-linux-gnueabihf-gcc
    export STRIP=arm-linux-gnueabihf-strip

    # Compile all to dist/
    ./clean.sh
    ./build.sh
    ./dist.sh

    # Patch wrapper script to have a process name consistent with the
    # path of the symlink in /opt/bin
    sed -i 's#exec ./plato#exec -a /opt/bin/plato ./plato#' dist/plato.sh
}

package() {
    # Install plato data in /opt/lib/plato
    install -d "$pkgdir"/opt/lib
    cp -r "$srcdir"/dist "$pkgdir"/opt/lib/plato

    # Link /opt/bin/plato to /opt/lib/plato/plato.sh
    install -d "$pkgdir"/opt/bin
    ln -s /opt/lib/plato/plato.sh "$pkgdir"/opt/bin/plato

    # Link media dir to /home/root/plato-media
    rmdir "$pkgdir"/opt/lib/plato/media
    ln -s /home/root/plato-media "$pkgdir"/opt/lib/plato/media

    # Link Settings.toml to /opt/etc/plato.toml
    install -d "$pkgdir"/opt/etc
    ln -s /opt/etc/plato.toml "$pkgdir"/opt/lib/plato/Settings.toml

    install -D -m 644 "$srcdir"/oxide "$pkgdir"/opt/etc/draft/plato.draft
    install -D -m 644 "$srcdir"/oxide-icon.png "$pkgdir"/opt/etc/draft/icons/plato.png
}

configure() {
    local mediadir=/home/root/plato-media

    if [[ ! -d $mediadir ]]; then
        # This directory should not be tracked by opkg
        # so that its contents are kept after removing
        mkdir "$mediadir"
        echo ""
        echo "Place your media files for plato in '$mediadir'"
        echo ""
    else
        # Convert old library metadata format for version 0.9.14
        # (see <https://github.com/baskerville/plato/releases/tag/0.9.14>)
        local metadata_file="$mediadir"/.metadata.json
        local key_len
        [[ -f $metadata_file ]] && key_len="$(jq --raw-output 'keys[]' "$metadata_file" | wc -L)" || key_len=-1

        if [[ "$key_len" -gt 16 ]]; then
            local metadata_file_bak
            metadata_file_bak="$(mktemp "$metadata_file".bak.XXXXXXXX)"

            echo ""
            echo "In Plato 0.9.14 the metadata format for libraries changed."
            echo "Found existing metadata file in '$metadata_file'. Will update it automatically..."

            # Routine is based on baskerville's migrate-hex_keys.py (from the release page)
            # Rewritten in bash to only require jq rather than python.
            mv "$metadata_file" "$metadata_file_bak"
            local change_cmds=""
            local del_list=""

            while read -r key; do
                hex_key="$(printf %016X "$key")"
                [[ -z "$del_list" ]] || del_list="$del_list, "
                del_list="$del_list.[\"$key\"]"
                [[ -z "$change_cmds" ]] || change_cmds="$change_cmds | "
                change_cmds="$change_cmds.[\"$hex_key\"] = .[\"$key\"]"
            done <<< "$(jq --raw-output 'keys[]' "$metadata_file_bak")"

            # Create updated json file
            jq "$change_cmds | del($del_list)" "$metadata_file_bak" > "$metadata_file"

            echo "Update complete. Backup of previous version created in '$metadata_file_bak'."
            echo ""
        fi
    fi
}
